/*
 * Project: 24ClockWidget
 * Copyright (C) 2009 rdrrlabs gmail com,
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.rdrrlabs.a24clock.prefs;

import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.Button;

import com.alfray.a24clock.R;
import com.rdrrlabs.a24clock.app.ClockApp;
import com.rdrrlabs.a24clock.error.ExceptionHandler;
import com.rdrrlabs.a24clock.error.ExceptionHandlerActivity;
import com.rdrrlabs.a24clock.stats.AgentWrapper;
import com.rdrrlabs.a24clock.stats.AgentWrapper.Event;
import com.rdrrlabs.a24clock.ui.IntroActivity;

/**
 * Activity to configure global clock prefs.
 */
public class GlobalPrefsUI extends PreferenceActivity {

    public static final String TAG = GlobalPrefsUI.class.getSimpleName();
    @SuppressWarnings("unused")
    private static final boolean DEBUG = true;

    private ExceptionHandler mExceptionHandler;
    private ClockApp mApp;
    private PrefsValues mPrefValues;
    private AgentWrapper mAgent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mExceptionHandler = new ExceptionHandler(this);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.global_prefs);
        addPreferencesFromResource(R.xml.global_prefs);
        setTitle("24 Clock - Global Options");

        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mApp = (ClockApp) getApplicationContext();
        mPrefValues = mApp.getPrefsValues(-1);
        initButtons();

        // TEMP DEBUG
        for (String s : new String[] { "3x1", "4x1", "4x2" }) {
            Preference p = findPreference("scale_" + s);
            if (p != null) {
                p.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                    @Override
                    public boolean onPreferenceChange(Preference preference, Object newValue) {
                        mApp.clearDigitsBmps();
                        return true;
                    }
                });
            }
        }
    }

    /** Same as {@link ExceptionHandlerActivity#onStart} */
    @Override
    protected void onStart() {
        if (mExceptionHandler == null) {
            mExceptionHandler = new ExceptionHandler(this);
        }
        super.onStart();

        // Play the initial sound if requested by the prefs and if this
        // is a real start, not a configuration change
        if (getLastNonConfigurationInstance() == null) {
            if (mPrefValues.useOptionsSound() && !mPrefValues.useGlobalMute()) {
                playSound();
            }
        }

        displayIntroDelayed();

        mAgent = new AgentWrapper();
        mAgent.start(this);
        mAgent.event(Event.GlobalOptions);
    }

    /** Same as {@link ExceptionHandlerActivity#onStop} */
    @Override
    protected void onStop() {
        mAgent.stop(this);

        super.onStop();
        if (mExceptionHandler != null) {
            mExceptionHandler.detach();
            mExceptionHandler = null;
        }
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        // We return a random object, just to detect the next start
        // will be due to a config change (and avoid playing the sound)
        return new Object();
    }

    private void playSound() {

        final View v = findViewById(android.R.id.list);
        if (v != null) {
            final ViewTreeObserver obs = v.getViewTreeObserver();
            obs.addOnPreDrawListener(new OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    mApp.playSound(R.raw.startup_low, 1);
                    ViewTreeObserver obs2 = v.getViewTreeObserver();
                    obs2.removeOnPreDrawListener(this);
                    return true;
                }
            });
        }
    }

    private void displayIntroDelayed() {
        if (!mApp.isFirstStart()) return;

        final View v = findViewById(android.R.id.list);
        if (v != null) {
            final ViewTreeObserver obs = v.getViewTreeObserver();
            obs.addOnPreDrawListener(new OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    if (!mPrefValues.isIntroDismissed()) {
                        displayIntro();
                        mApp.setFirstStart(false);
                    }

                    ViewTreeObserver obs2 = v.getViewTreeObserver();
                    obs2.removeOnPreDrawListener(this);
                    return true;
                }
            });
        }
    }

    private void displayIntro() {
        Intent i = new Intent(this, IntroActivity.class);
        startActivityForResult(i, 0);
    }

    private void initButtons() {
        Button b = (Button) findViewById(R.id.more);
        if (b != null) {
            b.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    displayIntro();
                }
            });
        }
    }
}
